$(function() {
    // 初始化富文本编辑器
    initEditor()
        // 1. 初始化图片裁剪器
    var $image = $('#image')

    // 2. 裁剪选项
    var options = {
        aspectRatio: 1,
        preview: '.img-preview'
    }

    // 3. 初始化裁剪区域
    $image.cropper(options)
    let form = layui.form
    let layer = layui.layer
    initCate()

    function initCate() {
        $.ajax({
            method: 'get',
            url: '/my/cate/list',
            success: function(res) {
                if (res.code !== 0) {
                    return layer.msg('获取分类列表失败！')
                }
                let htmlStr = template('tpl-cate', res)
                $('[name=cate_id]').html(htmlStr)
                form.render()
            }
        })
    }
    $('#btnChooseImg').on('click', function() {
        $('#coverFile').click()
    })
    let file = null
    $('#coverFile').on('change', function(e) {
        let fileList = e.target.files
        if (fileList.length === 0) {
            return layer.msg('请选择图片！')
        }
        file = fileList[0]
        let newImgURL = URL.createObjectURL(file)
        $image
            .cropper('destroy') // 销毁旧的裁剪区域
            .attr('src', newImgURL) // 重新设置图片路径
            .cropper(options) // 重新初始化裁剪区域
    })
    let art_state = '已发布'
    $('#btnSave2').on('click', function() {
        art_state = '草稿'
    })
    $('#form_pub').on('submit', function(e) {
        e.preventDefault()
        let fd = new FormData($(this)[0])
        fd.append('cover_img', file)
        fd.append('state', art_state)
        publishArt(fd)
    })

    function publishArt(fd) {
        $.ajax({
            method: 'post',
            url: '/my/article/add',
            data: fd,
            contentType: false,
            processData: false,
            success: function(res) {
                if (res.code !== 0) {
                    return layer.msg('发布文章失败！')
                }
                layer.msg('发布文章成功！')
                $(window.parent.document.querySelector('#artList')).click()
            }

        })
    }
})